package com.monkeygroup.mygoplus.view.home.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.adapter.LoopPagerAdapter;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.base.BaseActivity;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.monkeygroup.mygoplus.common.utils.DateUtils;
import com.monkeygroup.mygoplus.common.utils.MapChartUtil;
import com.monkeygroup.mygoplus.common.utils.StringUtil;
import com.monkeygroup.mygoplus.http.RequestUrl;
import com.monkeygroup.mygoplus.http.ThingsHttpModel;
import com.monkeygroup.mygoplus.thing.vo.CommunityVO;
import com.monkeygroup.mygoplus.thing.vo.MyImageVO;
import com.monkeygroup.mygoplus.thing.vo.RentVO;
import com.monkeygroup.mygoplus.thing.vo.UserVO;
import com.monkeygroup.mygoplus.view.home.activity.sell.ThingsCarportDetailActivity;
import com.monkeygroup.mygoplus.view.home.fragment.HomeFragment;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by admin on 2017/6/10.
 */

public class CommunityDetailActivity extends BaseActivity implements View.OnClickListener,OnMapReadyCallback {

    public static void gotoActivity(Activity activity,String param,String area,String areaname) {
        Intent intent = new Intent(activity,
                CommunityDetailActivity.class);

        intent.putExtra("param", param);
        intent.putExtra("area", area);
        intent.putExtra("areaname", areaname);
        activity.startActivity(intent);
    }

    private LayoutInflater inflater;

    private Activity activity;
    private ImageView imgBack;
    private TextView txtTitle;

    private TextView txtName,txtImgSize,txtContact,txt_sell_price,txt_num,txt_rent_price,txt_rent_num,text_detail_addr,text_things_detail_storey,text_things_detail_cartport_have,
            text_things_detail_lift,text_things_detail_fee,text_things_detail_fitting,text_things_detail_completeyear,text_things_detail_type,
            text_things_detail_direction,text_things_detail_communityname,txt_introduce,txt_facility,txt_totential;

    private CommunityVO propertyModel;
    private List<RentVO> communityProperty;
    //請求
    private ThingsHttpModel httpThingsModel;
    private Map<String,String> param;
    //取得社区的物件列表
    private ThingsHttpModel CommunityHttpThingsModel;
    //行情
    private ThingsHttpModel priceuseHttpThingsModel;
    //折线图
    private ThingsHttpModel lineHttpThingsModel;
    private String seq;

    private LineChart lineChart;
    private PieChart pieChart,first_pieChart;

    private RollPagerView viewPager;
    private ImageView[] mImageViews;
    ImageLoader loader;
    DisplayImageOptions options;

    private String areaname;

    @Override
    public void onClick(View view) {

    }

    @Override
    public void setContentView() {
        setContentView(R.layout.community_detail); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void initView() {
        activity = CommunityDetailActivity.this;
        inflater = LayoutInflater.from(CommunityDetailActivity.this);

        txtName = (TextView) findViewById(R.id.text_things_detail_name);

        imgBack = (ImageView) findViewById(R.id.img_back);
        txtTitle = (TextView) findViewById(R.id.txt_title);
        txtTitle.setText("社區資訊");

        param = new HashMap<String,String>();
        txtImgSize = (TextView) findViewById(R.id.viewPager_things_all);
        txtContact = (TextView) findViewById(R.id.text_detail_contact);
        txt_sell_price= (TextView) findViewById(R.id.txt_sell_price);
        txt_num= (TextView) findViewById(R.id.txt_num);
        txt_rent_price= (TextView) findViewById(R.id.txt_rent_price);
        txt_rent_num= (TextView) findViewById(R.id.txt_rent_num);

        text_detail_addr= (TextView) findViewById(R.id.text_detail_addr);
        text_things_detail_storey= (TextView) findViewById(R.id.text_things_detail_storey);
        text_things_detail_cartport_have= (TextView) findViewById(R.id.text_things_detail_cartport_have);
        text_things_detail_lift= (TextView) findViewById(R.id.text_things_detail_lift);
        text_things_detail_fee= (TextView) findViewById(R.id.text_things_detail_fee);
        text_things_detail_fitting= (TextView) findViewById(R.id.text_things_detail_fitting);
        text_things_detail_completeyear= (TextView) findViewById(R.id.text_things_detail_completeyear);
        text_things_detail_type= (TextView) findViewById(R.id.text_things_detail_type);
        text_things_detail_direction= (TextView) findViewById(R.id.text_things_detail_direction);
        text_things_detail_communityname= (TextView) findViewById(R.id.text_things_detail_communityname);

        txt_introduce= (TextView) findViewById(R.id.txt_introduce);
        txt_facility= (TextView) findViewById(R.id.txt_facility);
        txt_totential= (TextView) findViewById(R.id.txt_totential);

        lineChart= (LineChart) findViewById(R.id.lineChart);
        pieChart= (PieChart) findViewById(R.id.pieChart);
        first_pieChart= (PieChart) findViewById(R.id.first_pieChart);


        Intent intent = this.getIntent();
        Bundle bundle =  intent.getExtras();
        seq = bundle.getString("param");
        String area= bundle.getString("area");
        areaname= bundle.getString("areaname");

        param.put("seq",seq);
        param.put("area",area);
        param.put("month","7");
        param.put("end",DateUtils.currentMonth());

        param.put("field","comm_price_unitprice");


        Log.e("seq:::",seq+"::"+area);
        initRequest(param);
        CommunityHttpThingsModel.requestThings();
        httpThingsModel.communityRequestThings();
        priceuseHttpThingsModel.priceuseRequestThings();
        lineHttpThingsModel.priceuseRequestThings();
    }

    @Override
    public void setListener() {
        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void doEvent() {

    }

    private void initRequest(Map<String,String> param){

        httpThingsModel = new ThingsHttpModel(RequestUrl.getCommunityDetailPropertyUrl,param,
                new ThingsHttpModel.SimpleOnHttpRequestListener() {
                    @Override
                    public void onRequestFinished(String resultCode, Integer timestamp) {

                    }

                    @Override
                    public void onRequestFinished(String resultCode, Object property, Object user, Object users, Object circuit, Object img) {


                    }

                    @Override
                    public void onBuildingRequestFinished(String resultCode, Object building, Object user, Object users, Object circuit, Object img) {

                    }

                    @Override
                    public void onCommunityRequestFinished(String resultCode, Object community, Object user, Object users, Object circuit, Object img) {
                        Gson gson = new Gson();
                        List<MyImageVO> imgModel = gson.fromJson(gson.toJson(img), new TypeToken<List<MyImageVO>>() {
                        }.getType());
                        propertyModel = gson.fromJson(gson.toJson(community), new TypeToken<CommunityVO>() {
                        }.getType());
                        UserVO userVO = gson.fromJson(gson.toJson(user), new TypeToken<UserVO>() {
                        }.getType());
                        Log.e("getNamegetName===",""+propertyModel.getName());
                        setImage(imgModel);
                        setCommunityData();
                        // setUserInfo(userVO);
                    }
                }, true);

        CommunityHttpThingsModel= new ThingsHttpModel(RequestUrl.getCommunityPropertyUrl,param,
                new ThingsHttpModel.SimpleOnHttpRequestListener() {
                    @Override
                    public void onRequestFinished(String resultCode, Integer timestamp) {

                    }

                    @Override
                    public void onRequestFinished(String resultCode, Object property, Object user, Object users, Object circuit, Object img) {
                        Gson gson = new Gson();
                        communityProperty = gson.fromJson(gson.toJson(property), new TypeToken<List<RentVO>>() {
                        }.getType());
                        int saleNum=0;
                        int rentNum=0;
                        List<Float> maxSaleNum = new ArrayList<Float>();
                        List<Float> maxRentNum = new ArrayList<Float>();
                        for(int i=0;i<communityProperty.size();i++){
                            if(communityProperty.get(i).getSale()==1){
                                saleNum++;
                                Log.e("getSalepriceprice===",""+communityProperty.get(i).getSaleprice());
                                maxSaleNum.add(communityProperty.get(i).getSaleprice());
                            }
                            if(communityProperty.get(i).getRent()==1){
                                rentNum++;
                                maxRentNum.add(communityProperty.get(i).getRentprice());
                            }
                        }
                        Log.e("saleNumsaleNum==",""+saleNum);
                        Log.e("sizesizesizesize==",""+maxSaleNum.size());

                        txt_num.setText(String.valueOf(saleNum)+"间");
                        txt_rent_num.setText(String.valueOf(rentNum)+"间");
                        if(maxSaleNum.size()>0){
                            if(maxSaleNum.size()==1){
                                txt_sell_price.setText(String.format("待售：%s萬", String.valueOf(Collections.min(maxSaleNum))));

                            }
                            else{
                                txt_sell_price.setText(String.format("待售：%s~%s萬", String.valueOf(Collections.min(maxSaleNum)),String.valueOf(Collections.max(maxSaleNum))));

                            }

                        }
                        if(maxRentNum.size()>0){
                            if(maxRentNum.size()==1){
                                txt_rent_price.setText(String.format("待租：%s/月",String.valueOf(Collections.min(maxRentNum))));

                            }
                            else{
                                txt_rent_price.setText(String.format("待租：%s~%s/月",String.valueOf(Collections.min(maxRentNum)),String.valueOf(Collections.max(maxRentNum))));

                            }

                        }
                    }

                    @Override
                    public void onBuildingRequestFinished(String resultCode, Object building, Object user, Object users, Object circuit, Object img) {

                    }

                    @Override
                    public void onCommunityRequestFinished(String resultCode, Object community, Object user, Object users, Object circuit, Object img) {



                    }
                }, true);

        priceuseHttpThingsModel = new ThingsHttpModel(RequestUrl.getPriceusePropertyUrl ,param,
                new ThingsHttpModel.PriceuseSimpleOnHttpRequestListener() {
                    @Override
                    public void onRequestFinished(String resultCode, Integer timestamp) {

                    }

                    @Override
                    public void onRequestFinished(String resultCode, Object[] priceuse, Object priceusecnt, Object areausetext, Object[] areause,Object[] areagrid,Object areausecnt, Object[] ticks, Object[] timedata) {
                        if(areause!=null && areause.length==4){
                            Map<String, Float> pieValues = new HashMap<String, Float>();
                            List list = (List)areause[0];
                            List list1 = (List)areause[1];
                            List list2 = (List)areause[2];
                            List list3 = (List)areause[3];

                            Log.e("areause[0]areause[0]===",""+list.get(1)+list1.get(1)+list2.get(1)+list3.get(1));
                            if(list.get(1)==null){
                                list.set(1,"0");
                            }

                            if(list1.get(1)==null){
                                list1.set(1,"0");
                            }


                            if(list2.get(1)==null){
                                list2.set(1,"0");
                            }

                            if(list3.get(1)==null){
                                list3.set(1,"0");
                            }

                            pieValues.put("大楼",Float.parseFloat(String.valueOf(list.get(1))));
                            pieValues.put("公寓",Float.parseFloat(String.valueOf(list1.get(1))));
                            pieValues.put("套房",Float.parseFloat(String.valueOf(list2.get(1))));
                            pieValues.put("其他",Float.parseFloat(String.valueOf(list3.get(1))));
                            MapChartUtil.setPieChart(pieChart,pieValues,areaname,true,1);
                        }

                        if(areagrid!=null && areagrid.length==4){

                            Map<String, Float> pieValues = new HashMap<String, Float>();
                            List list = (List)areagrid[0];
                            List list1 = (List)areagrid[1];
                            List list2 = (List)areagrid[2];
                            List list3 = (List)areagrid[3];

                            Log.e("areagriid[0]===",""+list.get(1)+list1.get(1)+list2.get(1)+list3.get(1));
                            if(list.get(1)==null){
                                list.set(1,"0");
                            }

                            if(list1.get(1)==null){
                                list1.set(1,"0");
                            }


                            if(list2.get(1)==null){
                                list2.set(1,"0");
                            }

                            if(list3.get(1)==null){
                                list3.set(1,"0");
                            }

                            pieValues.put("二房",Float.parseFloat(String.valueOf(list.get(1))));
                            pieValues.put("三房",Float.parseFloat(String.valueOf(list1.get(1))));
                            pieValues.put("四房",Float.parseFloat(String.valueOf(list2.get(1))));
                            pieValues.put("五房",Float.parseFloat(String.valueOf(list3.get(1))));
                            MapChartUtil.setPieChart(first_pieChart,pieValues,areaname,true,2);


                        }
//                        List<Float> yXAxisValues = new ArrayList<Float>();
//                        yXAxisValues.add(Float.parseFloat("123"));
//                        yXAxisValues.add(Float.parseFloat("1223"));
//                        List<String> xAxisValue= new ArrayList<String>();
//                        xAxisValue.add("1");
//                        xAxisValue.add("2");
//                        List<String> titles= new ArrayList<String>();
//                        boolean showSetValues = true;
//                        MapChartUtil.setLineChart(lineChart,xAxisValue,yXAxisValues,"出售行情",showSetValues);
                    }





                },true);

        lineHttpThingsModel = new ThingsHttpModel(RequestUrl.getCommunitylineUrl ,param,
                new ThingsHttpModel.PriceuseSimpleOnHttpRequestListener() {
                    @Override
                    public void onRequestFinished(String resultCode, Integer timestamp) {

                    }

                    @Override
                    public void onRequestFinished(String resultCode, Object[] priceuse, Object priceusecnt, Object areausetext, Object[] areause,Object[] areagrid, Object areausecnt, Object[] ticks, Object[] timedata) {


                        Log.e("timedatatimedata==",""+(Map)timedata[0]);

                        List<Float> yXAxisValues = new ArrayList<Float>();
//                        yXAxisValues.add(Float.parseFloat("10"));
//                        yXAxisValues.add(Float.parseFloat("40"));
//                        yXAxisValues.add(Float.parseFloat("30"));
//                        yXAxisValues.add(Float.parseFloat("50"));
//                        yXAxisValues.add(Float.parseFloat("30"));
//                        yXAxisValues.add(Float.parseFloat("60"));
//                        yXAxisValues.add(Float.parseFloat("70"));
                        Map<Integer, Integer> map = (Map)timedata[0];

                        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {

                         //   System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                            yXAxisValues.add(Float.parseFloat(String.valueOf(entry.getValue())));
                        }
////                         for(int j=0;j<timedata.length;j++){
////                             yXAxisValues.add(Float.parseFloat(String.valueOf(timedata[j])));
////                         }
//                        //x轴
                        List<String> xAxisValue= new ArrayList<String>();
//                        xAxisValue.add(DateUtils.currentMonth()); xAxisValue.add(DateUtils.lastXMonth(1)); xAxisValue.add(DateUtils.lastXMonth(2));
//                        xAxisValue.add(DateUtils.lastXMonth(3)); xAxisValue.add(DateUtils.lastXMonth(4)); xAxisValue.add(DateUtils.lastXMonth(5));
//                        xAxisValue.add(DateUtils.lastXMonth(6));
// xAxisValue.add(DateUtils.lastXMonth(7)); xAxisValue.add(DateUtils.lastXMonth(8));
                          for(int i=0;i<ticks.length;i++){
                              xAxisValue.add(String.valueOf(ticks[i]).substring(0,7));
                          }
//
                        List<String> titles= new ArrayList<String>();
                        boolean showSetValues = true;
                        MapChartUtil.setLineChart(lineChart,xAxisValue,yXAxisValues,"出售行情",showSetValues);

                    }



                },true);
        //格局


    }

    private void setImage(List<MyImageVO> imgModel) {
        loader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.mipmap.img_mygoempty_nor3x)
                .showImageOnFail(R.mipmap.img_mygoempty_nor3x).cacheInMemory(true)
                .cacheOnDisc(true).displayer(new RoundedBitmapDisplayer(0))
                .build();
        List<String> imgs = new ArrayList<>();
        for (MyImageVO vo : imgModel) {
            if (vo.getCover() != 1&&imgs.size()<10) {
                imgs.add(vo.getPath());
            }
        }
        viewPager = (RollPagerView) findViewById(R.id.viewPager_things_all_img);
        viewPager.setAdapter(new ImageLoopAdapter(viewPager,imgs));
        mImageViews = new ImageView[imgs.size()];
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            viewPager.setHintView(new ColorPointHintView(activity, Color.parseColor("#DC473A"),Color.parseColor("#88ffffff")));
        }

    }

    private void setUserInfo(UserVO userVO) {
        txtContact.setText(userVO.getName() + " " + userVO.getTel());
    }

    private class ImageLoopAdapter extends LoopPagerAdapter {

        private List<String> imgs;
        public ImageLoopAdapter(RollPagerView viewPager,List<String> imgs) {

            super(viewPager);
            this.imgs=imgs;
        }

        @Override
        public View getView(ViewGroup container, int position) {
            SimpleDraweeView view = new SimpleDraweeView(container.getContext());
            view.setScaleType(SimpleDraweeView.ScaleType.FIT_XY);
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            view.setImageURI(Uri.parse(imgs.get(position)));
            return view;

        }

        @Override
        public int getRealCount() {
            return imgs.size();
        }


    }

    private void setCommunityData(){

        txtName.setText(propertyModel.getName());
        //  txt_sell_price.setText(String.format("",""));
        text_detail_addr.setText(propertyModel.getAddr());
        text_things_detail_storey.setText(propertyModel.getSquare());
        //格局
        text_things_detail_cartport_have.setText(propertyModel.getGrid());
        text_things_detail_lift.setText(propertyModel.getTotallive());
        //形態
        text_things_detail_fee.setText(propertyModel.getTypename());
        //公社比
        if(!StringUtil.isBlank(propertyModel.getLiverate())){
            text_things_detail_fitting.setText(propertyModel.getLiverate());
        }
        if(!StringUtil.isBlank(propertyModel.getManagefee())){
            text_things_detail_completeyear.setText(propertyModel.getManagefee());
        }

        text_things_detail_type.setText(propertyModel.getComplatedate());
        //建設
        text_things_detail_direction.setText(propertyModel.getConscomp());
        //層數
        text_things_detail_communityname.setText(propertyModel.getFloor());
        txt_introduce.setText(propertyModel.getIntroduce());
        txt_facility.setText(propertyModel.getFacility());

        txt_totential.setText(propertyModel.getTotential());
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        // LatLng positon = new LatLng(propertyModel.getLat(), propertyModel.getLng());
        LatLng positon = new LatLng(0, 0);
        googleMap.addMarker(new MarkerOptions().position(positon).title(""));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(positon));

    }
}
